package com.ljw;


import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;

import javax.swing.JFrame;


public class PhysicalEngine {
	public class Circle{
		public double x;
		public double y;
		
		public double Vx;
		public double Vy;
		
		public Circle(int x, int y){
			this.x = x;
			this.y = y;
			Vx = 0.2;
			Vy = 0;
		}
	}
	
	public JFrame frame;
	public Canvas canvas;
	public BufferStrategy bs;
	public ArrayList<Circle> shapes = new ArrayList<Circle>();
	public Thread physics;
	
	public PhysicalEngine(){
		physics = new Thread(){
			public void run(){
				while(true){
					for(Circle c : shapes){
						c.Vx -= c.Vx * 0.0003;
						c.Vy -= c.Vy * 0.0003;
						
						c.Vy += 0.001d;
						c.y += c.Vy;
						
						c.x += c.Vx;
						
						if(c.y+15 > 400){
							c.y = 400-15;
							c.Vy *= -0.8;
						}
						
						if(c.x < 0){
							c.x = 0;
							c.Vx *= -0.8;
						}
						
						if(c.x+15 > 550){
							c.x = 550-15;
							c.Vx *= -0.8;
						}
					}
					
					try {
						sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		shapes.add(new Circle(100, 100));
		
		physics.start();
		
		
		
		frame = new JFrame("Test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		
		canvas = new Canvas();
		canvas.setBackground(Color.WHITE);
		canvas.setSize(550, 400);
		frame.add(canvas);
		
		canvas.createBufferStrategy(2);
		bs = canvas.getBufferStrategy();
		
		frame.pack();
		
		frame.setLocationRelativeTo(null);
		
		while(true){
			Graphics g = bs.getDrawGraphics();
			g.clearRect(0, 0, 550, 400);
			for(Circle c : shapes){
				g.fillOval((int)c.x, (int)c.y, 15, 15);
			}
			
			if(!bs.contentsLost())bs.show();
		}
	}
	
	public static void main(String[] ar){
		new PhysicalEngine();
	}
}